import {View, StyleSheet} from 'react-native';
import {ObserverButton, TextInput, Tabs, ObserverText} from '../../components';
import React, {useState} from 'react';
import {AutoRegister, login, mobilelogin} from '../../services';
import {useGlobalStore, useUserInfoStore} from '../../mobx';
import {
  ACCOUNT_NUMBER,
  deviceId,
  dpw12,
  dpw14,
  dpw24,
  dpw48,
  dpw56,
  dpw8,
  NUMBER_OR_LETTER_6_12,
  PHONE_REG,
  USER_INFO,
} from '../../constants';
import {setItem} from '../../utils';
import {SvgLock, SvgPhone, SvgUser} from '../../components/svg';
import CodeCountDown from './CountDown';

const styles = StyleSheet.create({
  box: {
    marginBottom: dpw24,
  },
  smallTitle: {
    marginHorizontal: 'auto',
    marginTop: dpw24,
    marginBottom: dpw8,
  },
  iconbox: {
    position: 'absolute',
    left: -dpw12,
    top: -dpw12,
  },
});

const logonArr = [
  {
    placeholder: 'enterUsername',
    name: 'Account',
    maxLength: 22,
    before: (
      <View style={styles.iconbox}>
        <SvgUser scale={0.5} />
      </View>
    ),
  },
  {
    placeholder: 'enterPassword',
    name: 'Password',
    maxLength: 12,
    before: (
      <View style={styles.iconbox}>
        <SvgLock scale={0.5} />
      </View>
    ),
  },
];

const codeArr = [
  {
    placeholder: 'enterMobile',
    name: 'Mobile',
    maxLength: 11,
    before: (
      <View style={styles.iconbox}>
        <SvgPhone scale={0.5} />
      </View>
    ),
  },
  {
    placeholder: 'enterCode',
    name: 'Code',
    maxLength: 6,
  },
];

const PswSign = ({setData}: any) => {
  return (
    <View style={{marginHorizontal: dpw24}}>
      {logonArr.map(it => (
        <TextInput
          key={it.name}
          {...it}
          onChangeText={text =>
            setData((p: Record<string, any>) => ({...p, [it.name]: text}))
          }
        />
      ))}
    </View>
  );
};

const CodeSign = ({setData, mobile}: any) => {
  return (
    <View style={{marginHorizontal: dpw24}}>
      {codeArr.map(it => {
        if (it.name === 'Code') {
          return (
            <View key={it.name} style={{flexDirection: 'row'}}>
              <TextInput
                {...it}
                onChangeText={text =>
                  setData((p: Record<string, any>) => ({...p, [it.name]: text}))
                }
                boxStyle={{flex: 1}}
              />
              <CodeCountDown mobile={mobile} />
            </View>
          );
        }
        return (
          <TextInput
            key={it.name}
            {...it}
            onChangeText={text =>
              setData((p: Record<string, any>) => ({...p, [it.name]: text}))
            }
          />
        );
      })}
    </View>
  );
};

const logonRegistry = (Mobile: string) => [
  {
    id: 1,
    tKey: 'psw_sign',
    type: 'tab-title',
    children: <PswSign />,
    left: -dpw56,
  },
  {
    id: 2,
    tKey: 'code_sign',
    type: 'tab-title',
    children: <CodeSign mobile={Mobile} />,
    left: dpw48,
  },
];

const LogonForm = ({openModal}: any) => {
  const [{Account, Password, Mobile, Code}, setFormData] = useState({
    Account: '',
    Password: '',
    Mobile: '',
    Code: null,
  });
  const [actId, setActId] = useState(0);
  const {setUserInfo} = useUserInfoStore();
  const {changeToastKey} = useGlobalStore();

  // 保存用户信息
  const saveUserInfo = async (info: any) => {
    await setItem(USER_INFO, info);
    setUserInfo(info);
    if (openModal) openModal();
  };

  // 手机号/账号密码登录
  const onSubmit = () => {
    let api = null;
    let params: Record<string, any> | null = {};
    if (actId === 0) {
      if (!Account || !ACCOUNT_NUMBER.test(Account)) {
        changeToastKey('enterSureUsername');
        return;
      }
      if (!Password || !NUMBER_OR_LETTER_6_12.test(Password)) {
        changeToastKey('enterSureUsername');
        return;
      }
      api = login;
      params = {
        Account,
        Password,
        Mac: deviceId,
      };
    } else if (actId === 1) {
      if (!Mobile || !PHONE_REG.test(Mobile)) {
        changeToastKey('please_enter_correct_phone');
        return;
      }
      if (!Code) {
        changeToastKey('enterCode');
        return;
      }
      api = mobilelogin;
      params = {
        Mobile,
        Code,
        Mac: deviceId,
      };
    }
    if (api) {
      api(params)
        .then((res: any) => {
          saveUserInfo(res.Data);
        })
        .catch((err?: any) => {
          changeToastKey(err?.data?.Message);
        })
        .finally(() => {
          params = null;
          api = null;
        });
    }
  };

  // 自动登录
  const onAutoLogon = () => {
    AutoRegister({
      Mac: deviceId,
      SpreadCode: '',
    })
      .then((res: any) => {
        saveUserInfo(res.Data);
      })
      .catch((err?: any) => {
        changeToastKey(err?.data?.Message);
      })
      .finally(() => {});
  };

  return (
    <View style={styles.box}>
      <Tabs
        titles={logonRegistry(Mobile)}
        setData={setFormData}
        pid={actId}
        onChange={setActId}
        titleboxStyle={{justifyContent: 'center', marginBottom: dpw14}}
      />
      <View style={{marginHorizontal: dpw24, marginTop: dpw8}}>
        <ObserverButton
          onPress={onSubmit}
          tKey={actId === 0 ? 'logon' : 'reginLogin'}
          type="primary"
        />
        <View style={styles.smallTitle}>
          <ObserverText tKey="autoLogon" type="desc" />
        </View>
        <ObserverButton
          onPress={onAutoLogon}
          tKey="generateAccount"
          type="primary"
        />
      </View>
    </View>
  );
};

export default LogonForm;
